import serial #导入模块
import base64
import binascii
import time

maclist = []

def get_msg():
    rev_msg = ''
    empty_count = 0
    while True:
         str=ser.read().decode("gbk")
         print("get", str)
         if (str == "\n"):
             print("收到消息", rev_msg)
             break
         elif (str == ""):
             print("收到空格")
             empty_count = empty_count + 1
             if (empty_count >= 8):
                 return "timeout"
         rev_msg = rev_msg + str
    return rev_msg

def handle_app():
    print("start get mac")
    ser.write("GET_MAC\n".encode("gbk"))  # 写数据
    msg = get_msg()
    if (msg == "timeout"):
         print("GET_MAC timeout")
         return msg
    mac = msg.split("=")[1]
    if (maclist.count(mac) > 0):
        print("same chip ", mac)
        return "same_chip" + mac
    print("GET_MAC=",mac)
    #encodebytes = base64.b64encode(bytes.fromhex(uid))
    # SET_NAME_cmd = "SET_NAME=" + encodebytes.decode() + "\n"
    SET_NAME_cmd = "SET_NAME=ALKEID Cleaner\n"
    print("SET_NAME_cmd = ", SET_NAME_cmd)
    ser.write(SET_NAME_cmd.encode("gbk"))
    msg = get_msg()
    if (msg == "timeout"):
        print("SET_NAME timeout")
        return msg
    maclist.append(mac)
    time.sleep(4)
    return "ok"

try:

    a1 = bytes.fromhex("00530034584d530620343835")
    a2 = bytes.fromhex("005300")
    #print(bytes.fromhex("001083"))
    encodestr =  base64.b64encode(a1)

    #print(hex(int('ffffffffffffffffffffffff', 16)))

    print('a1=',base64.b64encode(a1))
    print('a2=',base64.b64encode(a2))
    #端口，GNU / Linux上的/ dev / ttyUSB0 等 或 Windows上的 COM3 等
    portx="COM14"
    #波特率，标准值之一：50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200
    bps=9600
    #超时设置,None：永远等待操作，0为立即返回请求结果，其他值为等待超时时间(单位为秒）
    timex=2
    # 打开串口，并得到串口对象
    ser=serial.Serial(portx,bps,timeout=timex)
    print("串口详情参数：", ser)

    print(ser.port)#获取到当前打开的串口名
    print(ser.baudrate)#获取波特率
    while True:
        result=ser.write("GET_STATUS\n".encode("gbk"))#写数据
        print("GET_STATUS CMD")
        msg = get_msg()
        if (msg == "timeout"):
            print("GET_STATUS timeout")
            continue
        if (msg == "STAT=BL"):
            result = ser.write("APP\n".encode("gbk"))  # 写数据
            print("APP CMD")
            msg = get_msg()
            if (msg == "timeout"):
                print("APP timeout")
                continue
            if (msg == "go to app"):
                time.sleep(2)
                handle_result = handle_app()
                if (handle_result != "ok"):
                    continue
        elif (msg == "STAT=APP"):
            handle_result = handle_app()
            if (handle_result != "ok"):
                continue

    print("---------------")
    ser.close()#关闭串口


except Exception as e:
    print("---异常---：",e)